#pragma once

#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/ssl.hpp>
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <string>
#include <memory>
#include <functional>
#include <vector>
#include <chrono>

class HttpsConnection : public std::enable_shared_from_this<HttpsConnection>
{
public:
    using ResponseCallback = std::function<void(const boost::beast::error_code&, const std::string&)>;

    // 构造函数
    HttpsConnection(boost::asio::io_context& io_context,
                    boost::asio::ssl::context& ssl_context,
                    const std::string& host,
                    const std::string& port = "443");

    ~HttpsConnection();

    // 同步连接（阻塞，完成 TCP+TLS handshake）
    void connect();

    // 同步发送请求，返回响应
    std::string sendRequest(const std::string& method,
                            const std::string& target,
                            const std::string& body = "",
                            const std::vector<std::pair<std::string,std::string>>& headers = {});

    // 异步发送请求，使用回调
    void asyncSendRequest(const std::string& method,
                          const std::string& target,
                          const std::string& body,
                          const std::vector<std::pair<std::string,std::string>>& headers,
                          ResponseCallback callback);

private:
    void closeConnection();

    boost::asio::io_context& io_context_;
    boost::asio::ssl::context& ssl_context_;
    boost::asio::ip::tcp::resolver resolver_;
    boost::beast::ssl_stream<boost::beast::tcp_stream> ssl_stream_;

    std::string host_;
    std::string port_;
    boost::beast::flat_buffer buffer_;
    bool connected_;
};
